position:absolute
時,其父元素不能是position:static
(fixed、relative..都行)left:0;right:0;
使absolute具有流體特性,再設定margin:0 auto
使其水平方向能夠根據寬度自適應相同值(居中),要記得給寬度哦!
left:50%;
使左上角的點由左而右移動50%總寬度的距離,再用transform: translateX(-50%)
往左移動子元素自身寬度的50%距離,使其水平置中。 //CSS(margin:0 auto)
.parent{
position: relative;
width: 500px;
height: 100px;
border:2px solid green;
}
.child{
position: absolute;
width: 100px;
height: 30px;
left:0;
right:0;
margin:0 auto;
border:2px solid blue;
}
//CSS(left:50% & translateX(-50%))
.parent{
position: relative;
width: 500px;
height: 100px;
border:2px solid green;
}
.child{
position: absolute;
width: 100px;
height: 30px;
left:50%;
transform: translateX(-50%);
border:2px solid blue;
}
<div class="parent">
<div class="child"></div>
</div>